package com.example.qxfw.common.util;

import com.alibaba.excel.EasyExcel;
import com.example.qxfw.common.listener.GenericDataListener;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/************************************
 *
 * @author : HuangDeYin Jolly
 * @since : JDK 11
 * @Date : 2023/7/7  星期五   13:21
 * @description : 此类用来 导入导出工具
 ***************************************/
public class EasyExcelUtil {

    public static <T> void exportDataToExcel(HttpServletResponse response, String fileName, String sheetName, List<T> dataList, Class<T> clazz) throws IOException {
        String contentType = "applicationnd.openxmlformats-officedocument.spreadsheetml.sheet";
        response.setContentType(contentType);
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(dataList);
    }

    public static <T> String importDataFromExcel(MultipartFile file, Class<T> clazz, GenericDataListener<T> listener) throws IOException {
        EasyExcel.read(file.getInputStream(), clazz, listener).sheet().doRead();
        return "success";
    }
}
